package com.victualler.business.customer.service.impl;

import com.victualler.business.customer.dto.PreCustomerInfoDto;
import com.victualler.business.customer.dto.dataview.MounthQuantityDto;
import com.victualler.business.customer.dto.print.PreCustomerPrintDto;
import com.victualler.business.customer.dto.request.weixin.WxOrderAddressDto;
import com.victualler.business.customer.dto.request.weixin.WxOrderItemDto;
import com.victualler.business.customer.dto.request.weixin.WxOrderRequestDto;
import com.victualler.business.customer.entity.PreCustomerItemDao;
import com.victualler.business.customer.entity.PreCustomerOrderDao;
import com.victualler.business.customer.repository.PreCustomerOrderQueryRepository;
import com.victualler.business.customer.repository.PreCustomerOrderRepository;
import com.victualler.business.customer.service.PreCustomerItemService;
import com.victualler.business.customer.service.PreCustomerOrderService;
import com.victualler.business.purchase.enums.CheckStateEnum;
import com.victualler.core.base.service.impl.BaseServiceImpl;
import com.victualler.core.common.enums.ChecKDataErrorEnum;
import com.victualler.core.config.dict.service.DictService;
import com.victualler.product.customer.entity.CustomerAddressDao;
import com.victualler.product.customer.entity.CustomerDao;
import com.victualler.product.customer.service.CustomerService;
import com.victualler.product.goods.service.GoodsTypeDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: Guoshichang
 * @Date: Create in 17:03 2018/4/5
 * @Discription:  Dict字典类型对应的服务层
 */
@Service
public class PreCustomerOrderServiceImpl extends BaseServiceImpl<PreCustomerOrderDao,PreCustomerOrderRepository,PreCustomerOrderQueryRepository> implements PreCustomerOrderService {


    @Autowired
    private PreCustomerItemService itemService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private DictService dictService;
    @Autowired
    private GoodsTypeDetailService goodsTypeDetailService;
    /**
     * @author Guoshichang
     * @since 13:39 on 2018/7/7.
     * @param id 预订单id
     * @Function  根据条件入参prePurchaseRequestDto动态分页查询权限
     */
    public PreCustomerInfoDto findInfo(Long id) {
        PreCustomerOrderDao orderDao = this.getById(id);
        List<PreCustomerItemDao> itemDaoList = this.itemService.getByParentId(id);
        return new PreCustomerInfoDto(orderDao,itemDaoList);
    }

    /**
     * @author Guoshichang
     * @since 13:39 on 2018/7/7.
     * @param orderInfoDto 预订单实体大对象
     * @Function  保存预订单实体大对象
     */
    @Transactional
    public void saveInfo(PreCustomerInfoDto orderInfoDto) {
        //如果是提交类型 则更新提交时间
        if (CheckStateEnum.UN_CHECK.getKey().equals(String.valueOf(orderInfoDto.getOrderDao().getCheckState()))) {
            orderInfoDto.getOrderDao().setCommitDate(new Date());
        }
        if(orderInfoDto.getOrderDao().getId() == null) {
            //生成订单号
            this.save(orderInfoDto.getOrderDao());
            String orderNo = "PCT" + new SimpleDateFormat("yyyyMMdd").format(new Date()) +"-"+ orderInfoDto.getOrderDao().getId();
            orderInfoDto.getOrderDao().setOrderNo(orderNo);
            //刷新字表数据
            for (PreCustomerItemDao itemDao : orderInfoDto.getItemDaoList()) {
                itemDao.setParentId(orderInfoDto.getOrderDao().getId());
            }
            this.itemService.saveAll(orderInfoDto.getItemDaoList());
        } else {
            //更新
            this.save(orderInfoDto.getOrderDao());
            //更新明细信息
            this.itemService.updateList(orderInfoDto.getItemDaoList(),orderInfoDto.getOrderDao().getId());
        }
    }

    /**
     * @author Guoshichang
     * @since 18:01 on 2018/10/9.
     * @param orderDao 审查大对象
     * @return
     * @Function
     */
    @Transactional
    public void check(PreCustomerOrderDao orderDao) {
        PreCustomerOrderDao saveObject = this.getById(orderDao.getId());
        saveObject.setCheckDate(new Date());
        saveObject.setCheckUser(orderDao.getCheckUser());
        saveObject.setCheckUserCode(orderDao.getCheckUserCode());
        saveObject.setCheckRemark(orderDao.getCheckRemark());
        saveObject.setCheckState(orderDao.getCheckState());
        this.save(saveObject);
    }


    /**
     * @author Guoshichang
     * @since 13:39 on 2018/7/7.
     * @param id 预订单id
     * @Function  删除草稿订单
     */
    @Transactional
    public void deleteInfo(Long id) {
        PreCustomerOrderDao orderDao = this.getById(id);
        //只有草稿数据允许删除
        if(CheckStateEnum.TEMP.getKey().equals(String.valueOf(orderDao.getCheckState()))) {
            //删除所有信息
            this.deleteById(id);
            this.itemService.deleteByParentId(id);
        } else {
            String stateName =  CheckStateEnum.getValue(String.valueOf(orderDao.getCheckState()));
            throw ChecKDataErrorEnum.createException(ChecKDataErrorEnum.DATA_ERROR,stateName + "状态不可删除!");
        }
    }
    /**
     * @author Guoshichang
     * @since 12:46 on 2018/11/14.
     * @param orderNo 订单号
     * @return 输出pdf的列表
     * @Function 根据订单号将明细数据输出到TXT文件的String字符串中 用于对接系统
     */
    public String getExportModelText(String orderNo){
        //查到List
        List<PreCustomerPrintDto> list = this.baseQueryRepository.getExportModelList(orderNo);
        StringBuffer result=new StringBuffer("");
        list.forEach(item -> {
            result.append(item.getBarCode()); //条形码
            result.append(",");
            result.append(item.getQuantity()); //数量
            result.append(",");
            result.append(item.getItemModel()); //口味备注
            result.append(",");
            result.append(item.getItemName()); // 商品名称
            result.append("\r\n");
        });
        return result.toString();
    }

    /**
     * @author Guoshichang
     * @since 12:46 on 2018/11/14.
     * @param orderNo 订单号
     * @return 输出pdf的列表
     * @Function
     */
    public List<PreCustomerPrintDto> getExportModelList(String orderNo) {
        //查到List
        List<PreCustomerPrintDto> list = this.baseQueryRepository.getExportModelList(orderNo);
        //字典值
        String codeValue = dictService.getDictByCodeType("SendType",list.get(0).getSendType()).getCodeValue();
        String formatDate = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm").format(new Date());
        list.forEach(item -> {
            item.setSendType(codeValue);
            item.setPrintDate(formatDate);
        });
        return list;
    }

    /**
     * @author Guoshichang
     * @since 12:00 on 2019/1/18.
     * @param wxOrderRequestDto 微信购物车下单大对象
     * @return 无
     * @Function  将微信报货单报货对象
     */
    @Transactional
    public void sendWeiXinOrder(WxOrderRequestDto wxOrderRequestDto) {
        //根据opid获取customerId
        CustomerDao customerDao = customerService.findInfoDtoByOpenId(wxOrderRequestDto.getOpenId()).getCustomerDao();
        //更新微信客户地址信息
        /**后端将保存/更新微信编辑的配送地址 */
        WxOrderAddressDto addressInfo = wxOrderRequestDto.getAddressInfo();
        String sendAddress = addressInfo.getProvinceName() + addressInfo.getCityName()
                + addressInfo.getCountyName() + addressInfo.getDetailInfo();
        CustomerAddressDao customerAddressDao = customerService.updateAddress(addressInfo.getUserName(), addressInfo.getTelNumber(), sendAddress, customerDao.getId());

        //将订货单对应系统报货单保存的大对象
        PreCustomerInfoDto preCustomerInfoDto = this.transfer(wxOrderRequestDto, customerDao,customerAddressDao);
        //保存订货单
        this.saveInfo(preCustomerInfoDto);
    }
    
    /**
     * @author Guoshichang   
     * @since 12:07 on 2019/1/18.
     * @param wxOrderRequestDto 微信大对象
     * @return 报货单实体对象
     * @Function  将微信购物车下单对象 转换为 客户报货预订单
     */
    private PreCustomerInfoDto transfer(WxOrderRequestDto wxOrderRequestDto,CustomerDao customerDao,CustomerAddressDao addressInfo){

    //子信息
        List<PreCustomerItemDao> preCustomerItemDaoList = new ArrayList<>();
        BigDecimal sumQuantity = BigDecimal.ZERO;
        for (WxOrderItemDto wxOrderItemDto : wxOrderRequestDto.getItemList()) {
            PreCustomerItemDao preCustomerItemDao = new PreCustomerItemDao();
            /**厂商id*/
            preCustomerItemDao.setVenderId(wxOrderItemDto.getVenderId());
            /**商品id*/
            preCustomerItemDao.setGoodsId(wxOrderItemDto.getGoodsModelDetailDao().getParentId());
            /**商品型号id*/
            preCustomerItemDao.setGoodsModelId(wxOrderItemDto.getGoodsModelId());
            /**数量*/
            preCustomerItemDao.setQuantity(new BigDecimal(wxOrderItemDto.getNum()));
            //累加
            sumQuantity = sumQuantity.add(preCustomerItemDao.getQuantity());

            preCustomerItemDaoList.add(preCustomerItemDao);
        }
    //主信息
        PreCustomerOrderDao orderDao = new PreCustomerOrderDao();
        /**用户id*/
        orderDao.setCustomerId(customerDao.getId());
        /**用户名称*/
        orderDao.setCustomerName(customerDao.getName());
        /**配送地址id*/
        orderDao.setCustomerAddressId(addressInfo.getId());
        /**联系人*/
        orderDao.setSendName(addressInfo.getName());
        /**联系电话*/
        orderDao.setSendPhone(addressInfo.getPhone());
        /**配送地址*/
        orderDao.setSendAddress(addressInfo.getAddress());
        /**配送类型*/
        orderDao.setSendType("SelfSend"); //默认自营配送
        /**订单总量*/
        orderDao.setSumQuantity(sumQuantity);
        /**备注*/
        orderDao.setReason(wxOrderRequestDto.getRemarks());
        /**经办人和制单人*/
        orderDao.setCreateUser("[系统生成]");
        orderDao.setCreateUserCode("00000000");
        orderDao.setMadeUser("[系统生成]");
        orderDao.setMadeUserCode("00000000");
        return new PreCustomerInfoDto(orderDao,preCustomerItemDaoList);
    }


    public List<MounthQuantityDto> getSumQuantityDataView() {
        return this.baseQueryRepository.getSumQuantityDataView();
    }

    /**
     * @author Guoshichang
     * @since 11:52 on 2019/1/31.
     * @param
     * @return
     * @Function 获得前三十天内销量top10商品
     */
    public List<MounthQuantityDto> getQuantityByGoods() {
        return this.baseQueryRepository.getQuantityByGoods();
    }
    /**
     * @author Guoshichang
     * @since 11:52 on 2019/1/31.
     * @param
     * @return
     * @Function 获得前三十天内销量top10的商家
     */
    public List<MounthQuantityDto> getQuantityByCustomer() {
        return this.baseQueryRepository.getQuantityByCustomer();
    }

}
